import cv2
import numpy as np

if __name__ == '__main__':
    # 1. 图片输入
    image_np = cv2.imread('paper.jpg')

    # 获取高度和宽度
    h = image_np.shape[0]
    w = image_np.shape[1]
    print(h, w)

    # 2. 单点旋转 + 3. 图片旋转
    angle = -45  # 旋转角
    scale = 1  # 缩放倍率
    # 构建仿射变换矩阵（2D）
    M = cv2.getRotationMatrix2D(
        (700, 700),  # 旋转点
        angle,  # 旋转角
        scale  # 缩放比例
    )
    print(M)

    # 4. 插值方法 + 5. 边缘填充方法
    rotation_image = cv2.warpAffine(
        image_np,  # 要应用变换的图像
        M,  # 仿射变换矩阵
        (image_np.shape[1] * 1, image_np.shape[0] * 1),  # 目标图像分辨率
    )
    # 2. 图片切割
    x_min, x_max = 200, 840
    y_min, y_max = 530, 950

    try:
        # 获取旋转后图像的尺寸
        h_rot, w_rot = rotation_image.shape[0], rotation_image.shape[1]
        if not (x_min >= 0 and y_min >= 0 and x_max < w and y_max < h and x_max > x_min and y_max > y_min):
            raise ValueError('ROI区域设定有误！！！')
        # 切片（左闭右开）
        ROI_image = rotation_image.copy()[y_min:y_max, x_min:x_max]
        # 把要切出的区域花个框
        line_width = 2  # 框的宽度
        # 画出范围
        cv2.rectangle(
            image_np,
            (x_min, y_min),
            (x_max, y_max),
            (0, 0, 255),
            line_width
        )
    except Exception as e:
        # 如果出错，弹出错误信息
        print('程序运行出错：', e)

    cv2.imshow('rotation_image', ROI_image)
    cv2.imwrite('rotation_image.jpg', ROI_image)
    cv2.waitKey(0)